﻿#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<vector>
using namespace std;

//数据流中的第k大元素
class KthLargest {
public:
    //建立一个小根堆
    priority_queue<int, vector<int>, greater<int>> heap;
    int _k;
    KthLargest(int k, vector<int>& nums) {
        _k = k;
        for (auto x : nums)
        {
            heap.push(x);
            if (heap.size() > _k)
            {
                heap.pop();
            }
        }
    }

    int add(int val) {
        heap.push(val);
        if (heap.size() > _k)
        {
            heap.pop();
        }
    }
};


//前k个高频单词
class Solution {
public:
    typedef pair<string, int> PSI;
    struct cmp
    {
        bool operator()(const PSI& a, const PSI& b)
        {
            if (a.second == b.second)//频次相同，建大堆
            {
                return a.first < b.first;
            }
            else
            {
                return a.second > b.second;
            }
        }
    };
    vector<string> topKFrequent(vector<string>& words, int k) {
        unordered_map<string, int> hash;
        //统计单词频数
        for (auto x : words)
        {
            hash[x]++;
        }
        //建堆
        priority_queue<PSI, vector<PSI>, cmp> heap;
        //入堆
        for (auto x : hash)
        {
            heap.push(x);
            if (heap.size() > k)
            {
                heap.pop();
            }
        }
        vector<string>ret(k);
        for (int i = k - 1; i >= 0; i--)
        {
            ret[i] = heap.top().first;
            heap.pop();
        }
        return ret;
    }
};